<template>
  <!-- <div class="wrapper">
    <Anchor :labelList="labels" activeId="row-01" labelWidth="100">
      <div class="line" id="row-01"> -->
        <div>
            <BreakSpace label="基本信息" :containerStyle="{ marginBottom: '10px' }" />
        <InfoBase
          ref="InfoBaseRef"
          v-on:childByValue="childByValue"
          v-model="value"
          @formSave="save"
        />
      <!-- </div> -->
      <!-- <div class="line" id="row-02"> -->
        <BreakSpace label="项目列表" :containerStyle="{ marginBottom: '10px' }" />
        <infoActivity ref="InfoActivityRef" v-model="value" />
      <!-- </div> -->
      <!-- <div class="line" id="row-03"> -->
        <BreakSpace label="营销素材列表" :containerStyle="{ marginBottom: '10px' }" />
        <infoGoods ref="InfoGoodsRef" v-model="value" />
      <!-- </div> -->
      <!-- <div class="line" id="row-04"> -->
        <BreakSpace label="经销商列表" :containerStyle="{ marginBottom: '10px' }" />
        <infoDealer ref="InfoDealerRef" v-model="value" />
      <!-- </div> -->
    <!-- </Anchor> -->
    <div class="dialogBottmView">
      <el-button @click="closeDialog">关 闭</el-button>
      <el-button
        @click="fenPeiDiaog"
        v-if="this.fenPeiStatus==true "
        :loading="saveLoading"
        type="primary"
      >分 配</el-button>
      <el-button
        @click="zuoFeiDiaog"
        v-if="typeof this.value.type!='undefined' && this.value.type==='edit' && this.btnZuoFeiStatus == true"
        type="primary"
      >作 废</el-button>
      <el-button
        @click="saveDialog"
        v-if="this.btnSaveStatus == true"
        :loading="saveLoading"
        type="primary"
      >保 存</el-button>
    </div>
  </div>
</template>

<script>
import { authority } from '@/utils/authMixin';
import { dictionary } from '@/utils/dictMixin';
import InfoBase from './infoBaseDistribution'; //基本信息
import infoActivity from '../commonForm/detail-infoActivity'; //项目列表
import infoGoods from '../commonForm/detail-infoGoods'; //营销素材列表
import infoDealer from '../commonForm/dealer'; //经销商列表
//api 项目新增
import { saveExcerciseAll, updateStatusBy, updateExcercise, updateAll } from '@/api/cms-api/projectOperating/program/push';
import { saveProjectMaterial, saveActivity, saveProjectOrg, updateProjectOrgStatus } from '@/api/cms-api/projectOperating/program/push';
import { fun_EditAll, deleteByProjectProgramId } from '@/api/cms-api/projectOperating/program/push';
import { insertDealers, deleteByDealerObj } from '@/api/cms-api/projectOperating/program/distribution';
import { getLoginUser } from '@/api/cms-api/projectOperating/program/departmentInquire';

// import {saveProjectMaterial,saveActivity}  from '@/api/projectOperating/program/push';

// import {insertProjOrg,saveExcerciseAll,updateProjectOrgStatus,insertDealers}  from '@/api/projectOperating/program/push';

export default {
  mixins: [authority, dictionary],
  components: {
    InfoBase,
    infoActivity,
    infoGoods,
    infoDealer
  },
  props: {
    value: {
      type: Object,
      required: true
    }
  },
  mounted() {
    // console.log(this.value)
  },
  data() {
    return {
      inClick: 0, //点击按钮的入口 0:保存,1:分配,2:作废
      loginUser: null, //登录用户信息
      btnZuoFeiStatus: false, //废除按钮
      btnSaveStatus: true, //保存按钮
      fenPeiStatus: true, //用于判断分配按钮是否显示
      caseUrlList: [],
      typeZ: '',
      result: {},
      saveLoading: false,
      infoBaseValue: {},
      infoGoodsRefValue: {},
      infoActivityRefValue: {},
      infoDealerRefValue: {},
      labels: [{ title: '基本信息', id: 'row-01' }, { title: '项目列表', id: 'row-02' }, { title: '营销素材列表', id: 'row-03' }, { title: '经销商列表', id: 'row-04' }]
    };
  },
  mounted() {
    console.log('wwwwwww', this.value.rowData.isNetworkIssued);
    // console.log("info.vm =>",this);
    if (this.value != null && typeof this.value.type != undefined && (this.value.type == 'edit' || this.value.type == 'show')) {
      //  console.log("Info'svalue的值2:", this.value);
      // this.init();
      this.loadUserInfo();
      //
      //事业部下发条件
      if (this.value.rowData.programIssuedChannel == 25301002 && this.value.rowData.orgStatus == 25281001) {
        this.fenPeiStatus = true;
      } else if (this.value.rowData.programIssuedChannel == 25301001 && this.value.rowData.orgStatus == 25281001) {
        //事业部下发条件
        this.fenPeiStatus = true;
      } else {
        this.fenPeiStatus = false;
        this.btnSaveStatus = false;
      }
    }
  },
  methods: {
    //监控子页面变量
    childByValue: function(childByValue) {
      // childValue就是子组件传过来的值
      this.saveLoading = childByValue;
    },
    //用于判断创建人和废除人是否一致
    async loadUserInfo() {
      this.loginUser = await getLoginUser({});
      //
      //  console.log("loadUserInfo = ",this.loginUser.data,"createdBy=",this.value);
      //25281003=作废,工单状态不为废除,则使用此过滤条件.否则,已废除的工单没有必要再次废除.
      if (
        (this.loginUser.data.userId == this.value.rowData.createdBy && this.value.rowData.orgStatus == 25281002 && this.value.rowData.programIssuedChannel == 25301002) ||
        (this.loginUser.data.userId == this.value.rowData.createdBy && this.value.rowData.orgStatus == 25281001 && this.value.rowData.programIssuedChannel == 25301002)
      ) {
        this.btnZuoFeiStatus = true;
      }
    },
    async fenPeiDiaog() {
      let dealer;
      dealer = this.$refs.InfoDealerRef.formValue;
      if (undefined == dealer.length || dealer.length <= 0) {
        this.$notify.warning({ title: '提示信息', message: '请选择经销商!' });
        return;
      }
      this.inClick = 1;
      // let status = 'xiaFa';
      this.$refs.InfoBaseRef.$refs.formPanel.SUBMIT_FORM();
    },
    async xiaFaFun() {
      this.infoBaseValue = this.$refs.InfoBaseRef.formValue;
      this.infoBaseValue.programStatus = 25281002;
      var arr = {};
      arr.programStatus = 25281002; //分配
      // debugger;
      arr.projectProgramId = this.value.rowData.projectProgramId;

      //this.value.rowData
      let res = null;
      if (arr.projectProgramId > 0) {
        res = await updateExcercise(this.value.rowData.projectProgramId, arr);
      } else {
        return;
      }

      //    console.log(res, 'res');
      if (res.resultCode === 200) {
        this.$notify.success({ title: '提示信息', message: '分配成功!' });
        // 重新加载
        this.closeDialog('refresh');
      } else {
        this.$notify.error({ title: '提示信息', message: res.errMsg || '分配失败!' });
        this.closeDialog();
      }
    },
    async zuoFeiDiaog() {
      this.inClick = 2;
      // this.$refs.InfoBaseRef.$refs.formPanel.SUBMIT_FORM();

      // let status = 'feiChu';

      // debugger
      this.infoBaseValue = this.$refs.InfoBaseRef.value.rowData;
      this.infoBaseValue.programStatus = 25281003;
      this.infoBaseValue.isNetworkIssued = this.value.rowData.isNetworkIssued;
      var arr = {};
      arr.programStatus = 25281003; //已废除
      arr.projectProgramId = this.value.rowData.projectProgramId;

      //this.value.rowData

      const res = await updateExcercise(this.value.rowData.projectProgramId, arr);

      //    console.log(res, 'res');
      if (res.resultCode === 200) {
        this.$notify.success({ title: '提示信息', message: '废除成功!' });
        // 重新加载
        this.closeDialog('refresh');
      } else {
        this.$notify.error({ title: '提示信息', message: res.errMsg || '废除失败!' });
        this.closeDialog();
      }
    },
    saveDialog() {
      this.saveDialog1();
    },
    //保存
    async saveDialog1() {
      let param;
      //this.$refs.InfoBaseRef.$refs.formPanel.SUBMIT_FORM();
      this.saveLoading = true;
      let v_projectProgramId;

      this.$refs.InfoBaseRef.$refs.formPanel.excuteFormData(this.$refs.InfoBaseRef.$refs.formPanel.form);
      this.infoBaseValue = this.$refs.InfoBaseRef.$refs.formPanel.form;
      let zq = this.infoBaseValue.hdzq;
      if (null != zq && zq.length > 0) {
        this.infoBaseValue.projectStartDate = zq[0];
        this.infoBaseValue.projectEndDate = zq[1];
      }
      this.infoBaseValue.orgId = this.$refs.InfoBaseRef.orgId; //事业部ID
      console.log('1111', this.infoBaseValue);
      //this.infoBaseValue = Object.assign({}, { programIssuedChannel: '25301002' }, this.infoBaseValue);
      if (typeof this.value.type != undefined && this.value.type === 'edit') {
        status = 'edit';
        v_projectProgramId = this.value.rowData.projectProgramId;
        if (this.inClick == 0) {
          this.infoBaseValue = this.editAndSaveInfoBase(v_projectProgramId, 25281001); //待分配
        } else if (this.inClick == 1) {
          //分配
          this.infoBaseValue = this.editAndSaveInfoBase(v_projectProgramId, 25281002); //已分配
        }
      } else if (typeof this.value.type != undefined && this.value.type === 'show') {
        status = 'show';
        v_projectProgramId = this.value.rowData.projectProgramId;
      } else {
        //添加 add
        status = 'add';

        // 保存附件,
        //25301001=方案分配渠道,主机厂分配
        if (this.inClick == 0) {
          this.infoBaseValue = this.editAndSaveInfoBase(-1, 25281001); //待分配25281001
        } else if (this.inClick == 1) {
          //已分配 25281002
          this.infoBaseValue = this.editAndSaveInfoBase(-1, 25281002);
        }
      }

      this.infoGoodsRefValue = this.$refs.InfoGoodsRef.formValue;
      this.infoActivityRefValue = this.$refs.InfoActivityRef.formValue;
      this.infoDealerRefValue = this.$refs.InfoDealerRef.formValue;
      if (undefined == this.infoGoodsRefValue.length) {
        this.infoGoodsRefValue = [];
      }
      if (undefined == this.infoDealerRefValue.length) {
        this.infoDealerRefValue = [];
      }
      //添加项目信息
      param = Object.assign({}, { infoBaseValue: this.infoBaseValue }, param);
      param = Object.assign({}, { infoGoodsRefValue: this.infoGoodsRefValue }, param);
      param = Object.assign({}, { infoActivityRefValue: this.infoActivityRefValue }, param);
      param = Object.assign({}, { infoDealerRefValue: this.infoDealerRefValue }, param);
      //是否是点击分配按钮(  这是添加按钮 1：分配  0：不是分配)
      param = Object.assign({}, { distributionFlag: 0 }, param);
      if (status == 'add') {
        //add
        // No.1
        v_projectProgramId = this.insertExcercise(param);
      } else if (status == 'edit') {
        this.infoBaseValue.projectProgramId = v_projectProgramId;
        //删除附件,再修改tm_project_program,添加附件.
        this.updateAllFun(v_projectProgramId, param);
      }
    },
    async save() {
      let param;
      let v_projectProgramId;
      this.infoBaseValue = this.$refs.InfoBaseRef.formValue;
      this.infoBaseValue.orgId = this.$refs.InfoBaseRef.orgId; //事业部ID
      let zq = this.infoBaseValue.hdzq;
      if (null != zq && zq.length > 0) {
        this.infoBaseValue.projectStartDate = zq[0];
        this.infoBaseValue.projectEndDate = zq[1];
      }
      // this.infoBaseValue = this.$refs.InfoBaseRef.value.rowData;
      //  debugger;
      if (typeof this.value.type != undefined && this.value.type === 'edit') {
        status = 'edit';
        v_projectProgramId = this.value.rowData.projectProgramId;
        // this.infoBaseValue =this.editAndSaveInfoBase(v_projectProgramId);
        if (this.inClick == 0) {
          this.infoBaseValue = this.editAndSaveInfoBase(v_projectProgramId, 25281001); //待分配
          //  console.log("this.infoBaseValue1=",this.infoBaseValue);
        } else if (this.inClick == 1) {
          //分配
          this.infoBaseValue = this.editAndSaveInfoBase(v_projectProgramId, 25281002); //已分配
          //  console.log("this.infoBaseValue2=",this.infoBaseValue);
        }
      } else if (typeof this.value.type != undefined && this.value.type === 'show') {
        status = 'show';
        v_projectProgramId = this.value.rowData.projectProgramId;
      } else {
        //添加 add
        status = 'add';

        // 保存附件,
        //25301001=方案分配渠道,主机厂分配
        //debugger
        if (this.inClick == 0) {
          this.infoBaseValue = this.editAndSaveInfoBase(-1, 25281001); //待分配25281001
        } else if (this.inClick == 1) {
          //已分配 25281002
          this.infoBaseValue = this.editAndSaveInfoBase(-1, 25281002);
        }
      }

      this.infoGoodsRefValue = this.$refs.InfoGoodsRef.formValue;
      this.infoActivityRefValue = this.$refs.InfoActivityRef.formValue;
      this.infoDealerRefValue = this.$refs.InfoDealerRef.formValue;
      if (undefined == this.infoGoodsRefValue.length) {
        this.infoGoodsRefValue = [];
      }
      if (undefined == this.infoDealerRefValue.length) {
        this.infoDealerRefValue = [];
      }
      //添加项目信息
      param = Object.assign({}, { infoBaseValue: this.infoBaseValue }, param);
      param = Object.assign({}, { infoGoodsRefValue: this.infoGoodsRefValue }, param);
      param = Object.assign({}, { infoActivityRefValue: this.infoActivityRefValue }, param);
      param = Object.assign({}, { infoDealerRefValue: this.infoDealerRefValue }, param);
      //是否是点击分配按钮
      param = Object.assign({}, { distributionFlag: 1 }, param);
      if (status == 'add') {
        //add
        // No.1
        v_projectProgramId = this.insertExcercise(param);
        //   console.log('v_projectProgramId=' + v_projectProgramId);
      } else if (status == 'edit') {
        this.infoBaseValue.projectProgramId = v_projectProgramId;
        //删除附件,再修改tm_project_program,添加附件.
        this.updateAllFun(v_projectProgramId, param);
      }
    },
    async updateAllFun(id, val) {
      if (id == '' && (val !== null && typeof val.length == 'undefined')) {
        return;
      } else {
        this.saveLoading  = true;
        const res = await updateAll(id, val);
        //   console.log(res, 'resupdateAll');
        if (res.resultCode === 200) {
          this.$notify.success({ title: '提示信息', message: '修改项目方案成功!' });
          // 重新加载
          this.closeDialog('refresh');
        } else {
          this.$notify.error({ title: '提示信息', message: res.errMsg || '修改项目方案失败!' });
          this.closeDialog();
        }
        this.saveLoading  = false;
      }
    },
    editAndSaveInfoBase(id, statusVal) {
      // debugger
      if (id > 0) {
        this.infoBaseValue.projectProgramId = id;
      }
      this.infoBaseValue.isNetworkIssued = this.value.rowData.isNetworkIssued;
      this.infoBaseValue.projectProgramOrgId = this.value.rowData.projectProgramOrgId; //营销方案事业部关系表ID
      this.infoBaseValue.programIssuedChannel = this.value.rowData.programIssuedChannel; //经销商
      // this.infoBaseValue = Object.assign({}, { projectStatus: statusVal }, this.infoBaseValue);
      this.infoBaseValue.programStatus = statusVal;

      if (this.infoBaseValue !== null) {
        let res = {};
        for (let i = 0; i < this.infoBaseValue.fileUrl.length; i++) {
          this.caseUrlList.push(Object.assign({}, { name: this.infoBaseValue.fileUrl[i].name }, { url: this.infoBaseValue.fileUrl[i].url }));
        }

        this.infoBaseValue = Object.assign({}, { fileUrl: this.caseUrlList }, this.infoBaseValue);
      }
      return this.infoBaseValue;
    },
    async funEditAll(id, val) {
      // val基础表信息.id是v_projectProgramId
      //val.length=0代表要删除所有tm_project_item对应记录
      if (id == '' && (val !== null && typeof val.length == 'undefined')) {
        return;
      } else {
        // debugger
        var l = val.length;
        for (var i = 0; i < val.length; i++) {
          val[i].projectProgramId = id;
          //  console.log('项目列表ArrayFunEditAll=', val[i], 'finalVal=', val);
        }
      }
      const res = await fun_EditAll(id, val);
      // debugger
      if (res.resultCode === 200 && res.data == true) {
        this.$notify.success({ title: '提示信息', message: '处理成功!' });
        // 重新加载
        this.closeDialog('refresh');
      } else {
        this.$notify.error({ title: '提示信息', message: res.errMsg || '处理失败!' });
        this.closeDialog();
      }
    },
    async insertExcercise(val) {
      //项目基础信息新增
      if (val !== null) {
        //   console.log('this.saveData=', val);
        // debugger

            if (val.infoActivityRefValue.length > 0) {

                if ((val.infoActivityRefValue[0].modelId+"").indexOf(',') == -1) { 

                }else {
                  
                  let modelList = val.infoActivityRefValue[0].modelId.split(',');
                  let modelNameList = val.infoActivityRefValue[0].modelName.split(',');
              
                    let array = new Array();
                  for (var i = 0 ; i < modelList.length ; i++) {
                          let object = {};
                          object.modelId = modelList[i];
                          object.modelName = modelNameList[i];
                          object.hdzq  = val.infoActivityRefValue[0].hdzq;
                          object.isMustDo = val.infoActivityRefValue[0].isMustDo;
                          object.itemAddress = val.infoActivityRefValue[0].itemAddress;
                          object.itemDate = val.infoActivityRefValue[0].itemDate;
                          object.itemEndDate = val.infoActivityRefValue[0].itemEndDate;
                          object.itemForm = val.infoActivityRefValue[0].itemForm;
                          object.itemName = val.infoActivityRefValue[0].itemName;
                          object.itemPurpose = val.infoActivityRefValue[0].itemPurpose;
                          object.itemStartDate = val.infoActivityRefValue[0].itemStartDate;
                          object.itemTheme = val.infoActivityRefValue[0].itemTheme;
                          object.projectItemId = val.infoActivityRefValue[0].projectItemId;
                          object.projectProgramId = val.infoActivityRefValue[0].projectProgramId;
                          object.status_zdj = val.infoActivityRefValue[0].status_zdj;
                            array.push(object);
                  }
                       val.infoActivityRefValue = array;
                }
         
        }
        this.saveLoading  = true;
        const res = await saveExcerciseAll(val);
        //  console.log(res, 'res');
        if (res.resultCode === 200) {
          this.$notify.success({ title: '提示信息', message: '新增项目方案成功!' });
          // 重新加载
          this.closeDialog('refresh');
        } else {
          this.$notify.error({ title: '提示信息', message: res.errMsg || '新增项目方案失败!' });
          this.closeDialog();
        }
        this.saveLoading  = false;
        return res.data.projectProgramId;
      }
    }, //新增项目列表
    async insertExcerciseList(val, id) {
      let res = {};
      //    console.log('新增项目列表:', val);
      if ((id == '' && (val !== null && typeof val.length == 'undefined')) || val.length == 0) {
        return;
      } else {
        // debugger
        var l = val.length;
        for (var i = 0; i < val.length; i++) {
          // if (val[i].projectProgramId != '') {
          //   delete val[i];
          //   l--;
          // } else {
          val[i].projectProgramId = id;
          // }

          //    console.log('项目列表Array=', val[i], 'final_val=', val);
        }
        //
        //   console.log('this.saveData项目列表=', val);
        if (l > 0) {
          console.log(val);
          res = await saveActivity(val);
          console.log(res);
          //  console.log(res, 'res');
          if (res.resultCode === 200) {
            this.$notify.success({ title: '提示信息', message: '项目列表新增成功!' });
            // 重新加载
            this.closeDialog('refresh');
          } else {
            this.$notify.error({ title: '提示信息', message: res.errMsg || '项目列表新增失败!' });
            this.closeDialog();
          }
        }

        return res.projectProgramId;
      }
    },
    async insertMaterial(val, id) {
      //营销素材新增
      //需要将项目编号id插入到营销素材表中,遍历一下插入
      if (val !== null) {
        for (var i = 0; i < val.length; i++) {
          val[i].projectProgramId = id;
          //   console.log('营销素材DataArray=', val[i]);
        }
        //  console.log('营销素材Data1=', val);
        const res = await saveProjectMaterial(val);
        // console.log(res, 'res');
        if (res.resultCode === 200) {
          this.$notify.success({ title: '提示信息', message: '营销素材列表0新增成功!' });
          // 重新加载
          this.closeDialog('refresh');
        } else {
          this.$notify.error({ title: '提示信息', message: res.errMsg || '营销素材列表0新增失败!' });
          this.closeDialog();
        }
        return res.data.projectProgramId;
      }
    },
    async fun_deleteByProjectProgramId(val, id) {
      if (val !== null && typeof val.length == 'undefined') {
        return;
      } else {
        for (var i = 0; i < val.length; i++) {
          val[i].projectProgramId = id;
        }
        const res = await deleteByProjectProgramId(id, val);
        // debugger
        if (res.resultCode === 200 && res.data == true) {
          this.$notify.success({ title: '提示信息', message: '营销素材列表保存成功!' });
          // 重新加载
          this.closeDialog('refresh');
        } else if (res.resultCode === 200 && res.data == false) {
          this.$notify.success({ title: '提示信息', message: '营销素材删除成功!' });
          this.closeDialog('refresh');
        } else {
          this.$notify.error({ title: '提示信息', message: res.errMsg || '营销素材列表保存失败!' });
          this.closeDialog();
        }
      }
    },
    async insertProjM(val, id) {
      //营销素材新增
      //需要将项目编号id插入到营销素材表中,遍历一下插入

      //  console.log('start:', id);
      if (val !== null && typeof val.length == 'undefined') {
        return;
      } else {
        for (var i = 0; i < val.length; i++) {
          val[i].projectProgramId = id;
          //   console.log('tr_project_program:DataArray=', val[i]);
        }
        //  console.log('营销素材Data0=', val);
        const res = await saveProjectMaterial(val);
        //  console.log(res, 'res');
        if (res.resultCode === 200) {
          this.$notify.success({ title: '提示信息', message: '营销素材列表新增成功!' });
          // 重新加载
          this.closeDialog('refresh');
        } else {
          this.$notify.error({ title: '提示信息', message: res.errMsg || '营销素材列表新增失败!' });
          this.closeDialog();
        }
        return res.data.projectProgramId;
      }
    },
    async insertDealersFun(val, id) {
      //需要将项目编号id插入到经销商表tr_project_org中,遍历一下插入

      // console.log('start:', id);
      if (val !== null && typeof val.length == 'undefined') {
        return;
      } else if (val.length == 0) {
        //需要删除所有的dealer信息

        const res = await deleteByDealerObj(id);
        //   debugger
        // console.log(res, 'resdeleteByDealerObj');
        // if (res.resultCode === 200) {
        //   this.$notify.success({ title: '提示信息', message: '删除经销商成功!' });
        //   // 重新加载
        //   this.closeDialog('refresh');
        // } else {
        //   this.$notify.error({ title: '提示信息', message: res.errMsg || '经销商删除失败!' });
        //   this.closeDialog();
        // }
      } else {
        for (var i = 0; i < val.length; i++) {
          val[i].projectProgramId = id;
          // if(this.inClick == 0){
          //     val[i].orgStatus = 25281001;
          // }else if(this.inClick == 1){
          //   val[i].orgStatus = 25281002;//只有主机厂下发的方案,在经销商才显示默认值:待分配
          // }

          //     console.log('1:事业部经销商DataArray=', val[i]);
        }
        //   console.log('经销商Data0=', val);
        const res = await insertDealers(val);
        //   console.log(res, 'res');
        if (res.resultCode === 200) {
          this.$notify.success({ title: '提示信息', message: '经销商新增成功!' });
          // 重新加载
          this.closeDialog('refresh');
        } else {
          this.$notify.error({ title: '提示信息', message: res.errMsg || '经销商新增失败!' });
          this.closeDialog();
        }
        return res.data.projectProgramId;
      }
    },
    //取消操作
    closeDialog(param) {
      this.value.type = '';

      this.$emit('close', { visible: false }, param);
    }
  }
};
</script>
<style scoped>
.wrapper {
  height: calc(100vh - 110px);
}
</style>
